
package com.foreveross.chameleon.activity;

import java.util.List;
import java.util.Set;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.foreveross.bsl.test.R;
import com.foreveross.chameleon.ModuleManager;
import com.foreveross.chameleon.config.ChameleonConfig;
import com.foreveross.chameleon.config.ChameleonConstants;
import com.foreveross.chameleon.listener.AppCheckUpdateListener;
import com.foreveross.chameleon.listener.AsyncTaskListener;
import com.foreveross.chameleon.manager.ModuleOperationService;
import com.foreveross.chameleon.manager.ModuleOperationService.ModuleOperationServiceBinder;
import com.foreveross.chameleon.model.ApplicationInfo;
import com.foreveross.chameleon.model.ModuleInfo;
import com.foreveross.chameleon.task.AppSyncCheckUpdateTask;
import com.foreveross.chameleon.task.ModuleSyncUpdateTask;
import com.foreveross.chameleon.utils.DeviceInfoUtil;
import com.foreveross.chameleon.utils.FileCopeTool;
import com.foreveross.chameleon.utils.PropertiesUtil;



/**
 * @description main logic activity
 * @author zhouzhineng
 * 
 */
public class MainActivity extends SupportCordovaActivity {
	private final String TAG = "MainActivity";

	protected IntentFilter mIntentFilter;
	protected ModuleOperationService mModuleOperationService = null;
	protected View mModuleLoadingView;
	protected TextView mModuleLoadingTips;
	protected int mTotolModuleCount;
	protected ProgressDialog mProgressDlg;
	protected AlertDialog needUpdateDialog;
	protected AlertDialog needDownloadDialog;
	protected boolean mShowUpdateDlg = false;
	protected boolean mFisrtPressBackKey = true;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.activity_main);
		getWindow().getDecorView().setBackgroundColor(Color.WHITE);
		//loadUrl("file:///android_asset/www/shake.html");
		localInit();
		//launchUrl = "file:///android_asset/www/test.html";
		//loadUrl(launchUrl);
	}
	
	
	protected void localInit() {
		PropertiesUtil prop = PropertiesUtil.readProperties(this, R.raw.cube);
		mShowUpdateDlg = prop.getBoolean(ChameleonConstants.SYNC_REMIND_DLG_SHOW, false);
		
		mIntentFilter = new IntentFilter();
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_START);
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_EXIT);
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_DOWNLOAD_START);
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_DOWNLOAD_FINISH);
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_DOWNLOAD_CANCEL);
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_DOWNLOAD_ERROR);
		mIntentFilter.addAction(ChameleonConstants.ACTION_MODULE_DOWNLOAD_START);
		mIntentFilter.addAction(ChameleonConstants.ACTION_MODULE_DOWNLOAD_FINISH);
		mIntentFilter.addAction(ChameleonConstants.ACTION_MODULE_DOWNLOAD_CANCEL);
		mIntentFilter.addAction(ChameleonConstants.ACTION_MODULE_DOWNLOAD_ERROR);
		mIntentFilter.addAction(ChameleonConstants.ACTION_MODULE_DOWNLOAD_PROGRESS_UPDATE);
		mIntentFilter.addAction(ChameleonConstants.ACTION_DOWNLOAD_COUNT_UPDATE);
		mIntentFilter.addAction(ChameleonConstants.ACTION_APP_REFRESH);
		mIntentFilter.addAction(ChameleonConstants.ACTION_MODULE_INSTALL);
		mIntentFilter.addAction(ChameleonConstants.ACTION_MODULE_UNINSTALL);
		mIntentFilter.addAction(ChameleonConstants.ACTION_MODULE_UPGRADE);
		mIntentFilter.addAction(ChameleonConstants.NETWORK_CONNECTED_STATE);
		
		registerReceiver(mMainReceiver, mIntentFilter);
		bindService(ModuleOperationService.getIntent(this),
				moduleServiceConnection, Context.BIND_AUTO_CREATE);
		loadMainModule();
		if(ChameleonConfig.NETWORK_OK) {
			syncMainModule();
			syncApp();
		}
	}

	@Override
	public void onResume() {
		registerReceiver(mMainReceiver, mIntentFilter);
		super.onResume();
	}

	@Override
	public void onDestroy() {
		unregisterReceiver(mMainReceiver);
		if (mModuleOperationService != null) {
			unbindService(moduleServiceConnection);
		}
		super.onDestroy();
	}

	@SuppressWarnings("deprecation")
	protected void noticeModuleDownloadStart(String identify) {
		appView.sendJavascript("moduleDownloadStart(\"" + identify + "\");");
	}
	
	@SuppressWarnings("deprecation")
	protected void noticeModuleDownloadFinish(String identify) {
		appView.sendJavascript("moduleDownloadFinish(\"" + identify + "\");");
	}
	
	@SuppressWarnings("deprecation")
	protected void updateModuleProgress(String identify,int progress) {
		appView.sendJavascript("updateModuleProgress(\""  +identify + "\",\""+ progress + "\");");
	}
	
	@SuppressWarnings("deprecation")
	protected void noticeModuleDownloadFail(String identify) {
		appView.sendJavascript("moduleDownloadFail(\"" + identify + "\");");
	}
	
	@SuppressWarnings("deprecation")
	protected void noticeNetworkStateChange(boolean state) {
		appView.sendJavascript("networkStateChange(\"" + state + "\");");
	}
	
	@SuppressWarnings("deprecation")
	protected void noticeModuleInstallState(String identify,boolean state) {
		appView.sendJavascript("moduleInstallState(\"" + identify + "\",\"" + state + "\");");
	}
	
	@SuppressWarnings("deprecation")
	protected void noticeModuleUninstallState(String identify,boolean state) {
		appView.sendJavascript("moduleUninstallState(\"" + identify + "\",\"" + state + "\");");
	}
	
	@SuppressWarnings("deprecation")
	protected void noticeModuleUpgradeState(String identify,boolean state,boolean isMainModule) {
		appView.sendJavascript("moduleUpgradeState(\"" + identify + "\",\"" + state + "\",\"" + isMainModule + "\");");
	}
	
	protected BroadcastReceiver mMainReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context ctx, Intent it) {
			// TODO Auto-generated method stub
			String action = it.getAction();
			String identify = it.getStringExtra("identify");
			ApplicationInfo localInfo = ApplicationInfo.getInstance(MainActivity.this);
			String mainModuleTag = localInfo.getMainModuleTag();
			if (action.equals(ChameleonConstants.ACTION_APP_START)) {
				Log.d(TAG, "app start...");
			} else if (action.equals(ChameleonConstants.ACTION_APP_EXIT)) {
				Log.d(TAG, "app exit...");
			} else if (action.equals(ChameleonConstants.ACTION_APP_DOWNLOAD_START)) {
				Log.d(TAG, "download start...");
			} else if (action.equals(ChameleonConstants.ACTION_APP_DOWNLOAD_FINISH)) {
				Log.d(TAG, "download finish...");
			} else if (action.equals(ChameleonConstants.ACTION_APP_DOWNLOAD_CANCEL)) {
				Log.d(TAG, "download cancel...");
			} else if (action.equals(ChameleonConstants.ACTION_MODULE_DOWNLOAD_START)) {
				Log.d(TAG, "download start...");
				if(identify != null) {
					noticeModuleDownloadStart(identify);
				}
			} else if (action.equals(ChameleonConstants.ACTION_MODULE_DOWNLOAD_FINISH)) {
				Log.d(TAG, "download finish...");
				//String mainModuleTag = PropertiesUtil.readProperties(MainActivity.this, R.raw.cube).getString("MAIN_MODULE_IDENTIFY", "");
				if(mainModuleTag.equals(identify)) {
					//loadMainModule();
				}
				if(identify != null) {
					noticeModuleDownloadFinish(identify);
				}
			} else if (action.equals(ChameleonConstants.ACTION_MODULE_DOWNLOAD_CANCEL)) {
				Log.d(TAG, "download cancel...");
			} else if (action.equals(ChameleonConstants.ACTION_MODULE_DOWNLOAD_PROGRESS_UPDATE)) {
				Log.d(TAG, "download progress update...");
				int progress = it.getIntExtra("progress", 0);
				updateModuleProgress(identify,progress);
			} else if(action.equals(ChameleonConstants.ACTION_MODULE_INSTALL)) {
				boolean state = it.getBooleanExtra(ChameleonConstants.MODULE_INSTALL_STATE, false);
				if(state && ChameleonConfig.REMOTE_MAIN_MODULE_TAG != null) {	//同步app主模块信息
					if( !localInfo.getMainModuleTag().equals(ChameleonConfig.REMOTE_MAIN_MODULE_TAG)) {
						localInfo.setMainModuleTag(ChameleonConfig.REMOTE_MAIN_MODULE_TAG);
						localInfo.save(localInfo);
					}
				}
				noticeModuleInstallState(identify,state);
			}else if(action.equals(ChameleonConstants.ACTION_MODULE_UNINSTALL)) {
				boolean state = it.getBooleanExtra(ChameleonConstants.MODULE_UNINSTALL_STATE, false);
				noticeModuleUninstallState(identify,state);
			}else if(action.equals(ChameleonConstants.ACTION_MODULE_UPGRADE)) {
				boolean state = it.getBooleanExtra(ChameleonConstants.MODULE_UPGRADE_STATE, false);
				boolean isMainModule = mainModuleTag.equals(identify);
				noticeModuleUpgradeState(identify,state,isMainModule);
			}else if (action.equals(ChameleonConstants.ACTION_DOWNLOAD_COUNT_UPDATE)) {
				Log.d(TAG, "download count update...");
			} else if (action.equals(ChameleonConstants.ACTION_APP_REFRESH)) {
				Log.d(TAG, "app refresh...");
			} else if(action.equals(ChameleonConstants.NETWORK_CONNECTED_STATE)) {
				boolean state = it.getBooleanExtra(ChameleonConstants.NETWORK_STATE, true);
				noticeNetworkStateChange(state);
			}
		}

	};

	protected String getMainModuleUrl() {
		String mainModuleUrl = null;
		return mainModuleUrl;
	}


	protected void syncApp() {
		ApplicationInfo curInfo = ApplicationInfo.getInstance(this);
		AppSyncCheckUpdateTask appUpdateTask = new AppSyncCheckUpdateTask(
				curInfo, new AppCheckUpdateListener(this));
		appUpdateTask.execute();
	}

	protected void syncMainModule() {
		ModuleSyncUpdateTask moduleSyncTask = new ModuleSyncUpdateTask(this,
				new AsyncTaskListener() {

					@Override
					public void onSucc(String result) {
						// TODO Auto-generated method stub
						ApplicationInfo remoteInfo = ApplicationInfo
								.buildApplication(result);
						Set<ModuleInfo> modules = remoteInfo.getModules();
						if(modules != null) {
							ModuleManager moduleMgr = ModuleManager
									.getInstance(getApplicationContext());
							//String mainModuleTag = PropertiesUtil.readProperties(MainActivity.this, R.raw.cube).getString("MAIN_MODULE_IDENTIFY", "");
							//ModuleInfo mainModule = ModuleManager.getInstance(MainActivity.this).getModule(mainModuleTag);
							ApplicationInfo localInfo = ApplicationInfo.getInstance(MainActivity.this);
							String mainModuleTag = localInfo.getMainModuleTag();
							ModuleInfo mainModule = localInfo.getModule(mainModuleTag);
							for(ModuleInfo module : modules) {
								if(module.getIdentifier().equals(mainModuleTag)) {
									if(module.getBuild() > mainModule.getBuild()) {
										moduleMgr.add2UpgradeList(module);
										moduleMgr.autoUpgrade(moduleMgr.getUpgradeList());
									}
								}
							}
						}
							
		
					}

					@Override
					public void onFail(int errcode) {
						// TODO Auto-generated method stub
						int errStr = R.string.network_disconnected;
						Toast.makeText(MainActivity.this, MainActivity.this.getString(errStr),
								Toast.LENGTH_LONG).show();
					}

				});
		moduleSyncTask.exec();
	}
	

	// 弹出更新提示
	public void showUpdateAlert(final List<ModuleInfo> updateModules) {
		StringBuffer sb = new StringBuffer();
		for (ModuleInfo module : updateModules) {
			sb.append("[" + module.getName() + " " + module.getVersion() + "]"
					+ "\n");
		}

		needUpdateDialog = new AlertDialog.Builder(this)
				.setTitle(getString(R.string.check_module_need_download))
				.setMessage(sb.toString())

				.setPositiveButton(getString(R.string.btn_ok), new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						ModuleManager.getInstance(getApplicationContext())
								.autoUpgrade(updateModules);
						needUpdateDialog.dismiss();
					}
				})
				.setNegativeButton(getString(R.string.btn_cancel), new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						needUpdateDialog.dismiss();
					}
				}).show();
	}

	// 弹出下载提示窗口
	public void showDownloadAlert(final List<ModuleInfo> downloadModules) {
		StringBuffer sb = new StringBuffer();
		// 提示需要下载的模块
		for (ModuleInfo module : downloadModules) {
			sb.append("[" + module.getName() + " " + " " + module.getVersion()
					+ "]" + "\n");
		}
		needDownloadDialog = new AlertDialog.Builder(this)

				.setTitle(getString(R.string.check_module_need_download))
				.setMessage(sb.toString())
				.setPositiveButton(getString(R.string.btn_ok), new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						ModuleManager.getInstance(getApplicationContext())
								.autoDownload(downloadModules);
						needDownloadDialog.dismiss();
					}
				})
				.setNegativeButton(getString(R.string.btn_cancel), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						needDownloadDialog.dismiss();
					}
				}).show();
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
		if(event.getKeyCode() == KeyEvent.KEYCODE_BACK && mFisrtPressBackKey) {
			mFisrtPressBackKey = false;
			if(appView.getUrl().equals(launchUrl) ) {
				AlertDialog isExit = new AlertDialog.Builder(this).create();
				isExit.setTitle(R.string.tip);
				isExit.setMessage(getString(R.string.ensure_exit));
				isExit.setButton(getString(R.string.btn_ok), listener);
				isExit.setButton2(getString(R.string.btn_cancel), listener);
				isExit.show();
				return true;
			} else {
				mFisrtPressBackKey = true;
			}
		}
		return super.dispatchKeyEvent(event);
	}
	

	DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()  
    {  
        public void onClick(DialogInterface dialog, int which) {  
            switch (which) {  
            case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序  
                finish();  
                break;  
            case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框  
            	mFisrtPressBackKey = true;
                break;  
            default:  
                break;  
            }  
        }  
    };    

	private ServiceConnection moduleServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mModuleOperationService = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mModuleOperationService = ((ModuleOperationServiceBinder) service)
					.getService();
			ModuleManager.getInstance(getApplicationContext())
					.setModuleOperationService(mModuleOperationService);
		}
	};

	private void loadMainModule() {
		if (DeviceInfoUtil.isPad()) {
			launchUrl = ChameleonConfig.PAD_MAIN_URL;
		} else {
			launchUrl = ChameleonConfig.PHONE_MAIN_URL;
		}
		
		ApplicationInfo localInfo = ApplicationInfo.getInstance(this);
		String mainModuleTag = localInfo.getMainModuleTag();
		FileCopeTool tool = new FileCopeTool(this);
		if (mainModuleTag != null && mainModuleTag.length() > 0) {
			boolean isExistMainTagFile = tool.isfileExist(ChameleonConfig.APP_PATH + "/www/" + mainModuleTag, "index.html");
			if(isExistMainTagFile) {
				launchUrl = "file://" + ChameleonConfig.APP_PATH + "/www/"
					+ mainModuleTag + "/index.html";
			}
		} 
		loadUrl(launchUrl);
	}
}
